{% extends 'knowledge/base.html' %}

{% block title %}创建知识库集合 - 知识库管理系统{% endblock %}

{% block content %}
<div class="max-w-2xl mx-auto">
    <div class="flex items-center mb-6">
        <a href="{% url 'knowledge:index' %}" class="text-neutral hover:text-primary mr-4">
            <i class="fa fa-arrow-left"></i>
        </a>
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">创建知识库集合</h2>
    </div>

    <div class="bg-white rounded-xl p-6 md:p-8 card-shadow">
        <form method="post" class="space-y-6">
            {% csrf_token %}
            <div>
                <label for="name" class="block text-sm font-medium text-gray-700 mb-1">集合名称</label>
                <input type="text" id="name" name="name" required
                       class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                       placeholder="输入知识库集合名称（例如：产品文档、技术手册）">
                <p class="mt-1 text-xs text-neutral">集合名称用于组织和分类文档，建议使用清晰且具有描述性的名称</p>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">元数据</label>
                <div class="mb-2">
                    <table class="w-full" id="metadata-table">
                        <thead>
                            <tr>
                                <th class="text-left pb-2 w-5/12">键</th>
                                <th class="text-left pb-2 w-5/12">值</th>
                                <th class="text-left pb-2 w-2/12"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="metadata-row">
                                <td class="pr-2 pb-2">
                                    <input type="text" class="metadata-key w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="键名">
                                </td>
                                <td class="pr-2 pb-2">
                                    <input type="text" class="metadata-value w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="值">
                                </td>
                                <td class="pb-2 text-center">
                                    <button type="button" class="delete-row px-2 py-1 text-red-500 hover:text-red-700 rounded-lg" title="删除行">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <div class="flex justify-start mb-2">
                    <button type="button" id="add-row" class="flex items-center px-3 py-1.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm">
                        <i class="fa fa-plus mr-1"></i> 添加字段
                    </button>
                </div>
                
                <!-- 隐藏的JSON输入框，用于表单提交 -->
                <input type="hidden" id="metadata" name="metadata">
                <p class="mt-1 text-xs text-neutral">添加键值对形式的元数据，用于对集合进行额外描述和分类</p>
                <p id="metadata-error" class="mt-1 text-xs text-red-500 hidden">元数据格式有误，请检查输入</p>
            </div>

            <div class="pt-4 flex justify-end space-x-3">
                <a href="{% url 'knowledge:index' %}" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                    取消
                </a>
                <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors shadow-sm">
                    创建集合
                </button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 获取元素
const metadataInput = document.getElementById('metadata');
const metadataError = document.getElementById('metadata-error');
const metadataTable = document.getElementById('metadata-table');
const addRowBtn = document.getElementById('add-row');
const form = metadataInput.closest('form');

// 添加新行
function addNewRow() {
    const tbody = metadataTable.querySelector('tbody');
    const newRow = document.createElement('tr');
    newRow.className = 'metadata-row';
    newRow.innerHTML = `
        <td class="pr-2 pb-2">
            <input type="text" class="metadata-key w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="键名">
        </td>
        <td class="pr-2 pb-2">
            <input type="text" class="metadata-value w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="值">
        </td>
        <td class="pb-2 text-center">
            <button type="button" class="delete-row px-2 py-1 text-red-500 hover:text-red-700 rounded-lg" title="删除行">
                <i class="fa fa-trash"></i>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
    
    // 为新行的删除按钮添加事件监听器
    const deleteBtn = newRow.querySelector('.delete-row');
    deleteBtn.addEventListener('click', function() {
        deleteRow(this);
    });
    
    // 为新行的输入框添加事件监听器
    const inputs = newRow.querySelectorAll('input');
    inputs.forEach(input => {
        input.addEventListener('input', updateMetadataJson);
    });
}

// 删除行
function deleteRow(button) {
    const row = button.closest('tr');
    const tbody = row.parentNode;
    
    // 如果只有一行，则清空输入而不是删除行
    if (tbody.children.length === 1) {
        const inputs = row.querySelectorAll('input');
        inputs.forEach(input => input.value = '');
    } else {
        row.remove();
    }
    
    updateMetadataJson();
}

// 将表格数据转换为JSON
function updateMetadataJson() {
    const rows = document.querySelectorAll('.metadata-row');
    const metadata = {};
    let isValid = true;
    
    rows.forEach(row => {
        const keyInput = row.querySelector('.metadata-key');
        const valueInput = row.querySelector('.metadata-value');
        const key = keyInput.value.trim();
        const value = valueInput.value.trim();
        
        if (key) {
            // 检查键是否重复
            if (metadata.hasOwnProperty(key)) {
                isValid = false;
                keyInput.classList.add('border-red-500');
            } else {
                keyInput.classList.remove('border-red-500');
                metadata[key] = value;
            }
        }
    });
    
    if (isValid) {
        metadataInput.value = Object.keys(metadata).length > 0 ? JSON.stringify(metadata) : '';
        metadataError.classList.add('hidden');
    } else {
        metadataError.textContent = '存在重复的键名，请修正';
        metadataError.classList.remove('hidden');
    }
    
    return isValid;
}

// 为添加行按钮添加事件监听器
addRowBtn.addEventListener('click', addNewRow);

// 为初始行的删除按钮添加事件监听器
document.querySelectorAll('.delete-row').forEach(button => {
    button.addEventListener('click', function() {
        deleteRow(this);
    });
});

// 为初始行的输入框添加事件监听器
document.querySelectorAll('.metadata-key, .metadata-value').forEach(input => {
    input.addEventListener('input', updateMetadataJson);
});

// 表单提交前验证
form.addEventListener('submit', function(e) {
    if (!updateMetadataJson()) {
        e.preventDefault();
    }
});

// 初始化
updateMetadataJson();
</script>
{% endblock %}